package com.jmectf.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import com.jme.math.Vector3f;
import com.jme.scene.CameraNode;
import com.jmectf.game.state.BattleState;
import com.jmectf.game.state.MenuState;
import com.jmectf.net.message.Synch3DMessage;
import com.jmex.editors.swing.settings.GameSettingsPanel;
import com.jmex.game.StandardGame;
import com.jmex.game.state.GameStateManager;
import com.jmex.terrain.TerrainPage;

public class BattleClient {

	static final String HOST_NAME = "69.143.81.207";
	Timer timer;
	Socket client;
	ObjectInputStream input;
	ObjectOutputStream output;
	StandardGame game;
	TerrainPage terrain;
	CameraNode camNode;
	BattleState gameState;


	public static void main(String[] args) {
		new BattleClient().run();
	}

	private void start() throws InterruptedException {
		game = new StandardGame("jmectf - BattleClient");
		if (GameSettingsPanel.prompt(game.getSettings())) {
			game.start();
			gameState = new BattleState(game);
			GameStateManager.getInstance().attachChild(gameState);
			gameState.setActive(true);
			MenuState menuState = new MenuState("MenuState", game);
			GameStateManager.getInstance().attachChild(menuState);
			menuState.setActive(false);
		}
	}

	public void run() {
		try {
			start();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		timer = new Timer();
		try {
			connectToServer();
			getStreams();
		} catch(Exception e) {
			e.printStackTrace();
		}
		if(client == null)
			System.exit(1);
		timer.scheduleAtFixedRate(new TimerTask() {
			// send server information
			public void run() {
				try {
					Vector3f pos = gameState.getPlayer().getLocalTranslation();
					sendData(pos.x + "," + pos.y + "," + pos.z);
				} catch (IOException e) {
					System.out.println("Server quit. Game ending...");
					System.exit(0);
				}
			}
		}, 100, 50);
	}

	private void connectToServer() throws UnknownHostException, IOException {
		client = new Socket(HOST_NAME, 4242);
		System.out.println("Connected to server.");
	}

	private void getStreams() throws IOException {
		output = new ObjectOutputStream(client.getOutputStream());
		output.flush();
		input = new ObjectInputStream(client.getInputStream());
		System.out.println("Extracted streams.");
	}

	private synchronized void sendData(String message) throws IOException {
		output.writeObject(new Synch3DMessage(message));
		output.flush();
	}


}
